/**
 * @param {*} number 距离顶部的距离(Number类型)
 * @param {*} time  滚动用时（Number类型）
 * @returns
 */
export const scrollToAnimationFn = (number: number = 0, time?: number) => {
	if (!time) {
	  document.body.scrollTop = document.documentElement.scrollTop = number
	  return number;
	}
	const spacingTime = 20 // 设置循环的间隔时间  值越小消耗性能越高
	let spacingInex = time / spacingTime // 计算循环的次数
	let nowTop = document.body.scrollTop || document.documentElement.scrollTop // 获取当前滚动条位置
	const everTop = (number - nowTop) / spacingInex // 计算每次滑动的距离
	const scrollTimer = setInterval(() => {
	  if (spacingInex > 0) {
		spacingInex--
		scrollToAnimationFn((nowTop += everTop))
	  } else {
		clearInterval(scrollTimer) // 清除计时器
	  }
	}, spacingTime)
};

/**
* 参数处理
* @param {*} params  参数
*/
export const tansParams = (params: any) => {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && typeof (value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && typeof (value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result
}

/**
 * 文本高亮
 * @param text 原始的文本内容
 * @param keyword 高亮的关键字
 * @returns 
 */
export const highlightText = (text: string, keyword: string) => {
	if (!keyword) {
		return text;
	}
	const regex = new RegExp(keyword, 'gi');
	return text.replace(regex, match => `<span class="highlight">${match}</span>`);
}

/**
 * 日期格式化
 * @param time 
 * @param pattern 
 * @returns 
 */
export const parseTime = (time: any, pattern: string) => {
	if (!time) {
		return null;
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
	let date: Date;
	if (typeof time === 'object') {
		date = time;
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = (time as String).replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm),'');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time.toString());
	}
	const formatObj: any = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}